﻿using B.S.BaseData.ErrorCode;
using B.S.BaseData.Manage.Api.Read.Apilaction.Command.ExportCommand;
using B.S.BaseData.Manage.Api.Read.Apilaction.Command.StoreCommand;
using B.S.BaseData.Manage.Api.Read.DTO;
using B.S.Passport.Domain;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;

namespace B.S.BaseData.Manage.Api.Read.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class StoreController : ControllerBase
    {
        private readonly IMediator mediator;
        private readonly ILogger<StoreController> logger;

        public StoreController(IMediator mediator, ILogger<StoreController> logger)
        {
            this.mediator = mediator;
            this.logger = logger;
        }
        /// <summary>
        /// 入库显示
        /// </summary>
        /// <param name="request">请求</param>
        /// <returns>取消</returns>
        [HttpGet]
        public async Task<ApiReqult<ApIPageing<ManagementModelDTO>>> StoreQuser([FromQuery] StoreQuserCommand request)
        {
            return await mediator.Send(request);
        }

        /// <summary>
        /// 入库Id查询
        /// </summary>
        /// <param name="request">请求</param>
        /// <returns>取消</returns>
        [HttpGet]
        public async Task<ApiReqult<List<ManagementModelDTO>>> StoreOnly([FromQuery] StoreOnlyCommand request)
        {
            try
            {
                logger.LogInformation("入库id查询开始");
                return await mediator.Send(request);
            }
            catch (Exception ex)
            {
                logger.LogError("入库id查询错误" + ex.Message);
                throw;
            }

        }
        /// <summary>
        /// 批量查询
        /// </summary>
        /// <param name="request">请求</param>
        /// <returns>取消</returns>
        [HttpGet]
        public async Task<ApiReqult<List<StoreDTO>>> ExportStoreQuser([FromQuery] ExportStoreQuserCommand request)
        {
            return await mediator.Send(request);
        }
        /// <summary>
        /// 导出
        /// </summary>
        /// <param name="commodityIds"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> ExportOrderList([FromQuery] List<int> id)
        {
            // 修正判断条件
            if (id == null || !id.Any())
            {
                return NotFound("未找到商品数据。");
            }
            var request = new ExportStoreQuserCommand { Id = id };
            var result = await ExportStoreQuser(request);
            using IWorkbook book = new XSSFWorkbook();
            ISheet sheet = book.CreateSheet("商品列表");
            IRow headerRow = sheet.CreateRow(0);

            // 设置表头
            string[] headers = { "订单号", "产品名称", "产品编号", "批次", "规格", "数量", "库位", "入库类型", "供应商", "制单人", "状态", "审核人", "审核时间" };
            for (int i = 0; i < headers.Length; i++)
            {
                headerRow.CreateCell(i).SetCellValue(headers[i]);
            }

            // 填充数据行
            int rowIndex = 1;
            foreach (var item in result.Data)
            {
                IRow row = sheet.CreateRow(rowIndex++);
                row.CreateCell(0).SetCellValue(item.InboundNum);
                row.CreateCell(1).SetCellValue(item.ProName ?? "");
                row.CreateCell(2).SetCellValue(item.ProId ?? "");
                row.CreateCell(3).SetCellValue(item.batch ?? "");
                row.CreateCell(4).SetCellValue(item.Specifications ?? "");
                row.CreateCell(5).SetCellValue(item.Quantity ?? "");
                row.CreateCell(6).SetCellValue(item.Binlocation ?? "");
                row.CreateCell(7).SetCellValue(item.Storage?.ToString() ?? "");
                row.CreateCell(8).SetCellValue(item.Supplier ?? "");
                row.CreateCell(9).SetCellValue(item.Creator ?? "");
                row.CreateCell(10).SetCellValue(item.OutAuditstatus?.ToString() ?? "");
                row.CreateCell(11).SetCellValue(item.Reviewer ?? "");
                row.CreateCell(12).SetCellValue(item.OutAuditTime?.ToString() ?? "");
            }

            using var ms = new MemoryStream();
            book.Write(ms);
            byte[] buffer = ms.ToArray();

            return File(buffer, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "商品列表.xlsx");
        }
        /// <summary>
        /// 查看库位
        /// </summary>
        [HttpGet]
        public async Task<ApiReqult<List<ManagementModelDTO>>> StoreFile([FromQuery] StoreFileCommand request)
        {
            return await mediator.Send(request);
        }
        /// <summary>
        /// 入库产品显示
        /// </summary>
        [HttpGet]
        public async Task<ApiReqult<ApIPageing<StoreproductDTO>>> Storeproduct([FromQuery] StoreproductCommand request)
        {
            try
            {
                return await mediator.Send(request);
            }
            catch (Exception ex)
            {
                logger.LogError("入库产品显示错误" + ex.Message);
                throw;
            }
        }
        /// <summary>
        /// 入库产品id查询
        /// </summary>
        [HttpGet]
        public async Task<ApiReqult<List<StoreproductDTO>>> StoreProductFile([FromQuery]StoreProductFileCommand request)
        {
            return await mediator.Send(request);
        }
    }
}
